package com.gitee.wsl.net.token


import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.headers
import io.ktor.client.request.request
import io.ktor.client.request.url
import io.ktor.client.statement.HttpResponse

import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import kotlin.coroutines.suspendCoroutine

abstract class AbstractApiTokenClient(
    val tokenKey:String,
    private val tokenStore: TokenStore,
    val client: HttpClient
) {
    private var isRefreshing = false
    private val failedQueue = mutableListOf<suspend () -> Unit>()

    // 请求拦截器
    fun addAuthHeader(request: HttpRequestBuilder) {
        request.headers {
            append(HttpHeaders.Authorization, "Bearer ${tokenStore.codeToken(tokenKey)}")
        }
    }

    // 核心刷新逻辑
    private suspend fun handleUnauthorized(originalRequest: HttpRequestBuilder): HttpResponse {
        if (isRefreshing) {
            // 将请求加入队列等待刷新完成
            return suspendCoroutine { continuation ->
                failedQueue.add {
                    continuation.resumeWith(runCatching {
                        client.request(originalRequest)
                    })
                }
            }
        }

        isRefreshing = true
        return try {
            // 刷新Token
            tokenStore.refreshToken(tokenKey)
            //val newTokens = tokenStore.refreshToken(tokenKey)
            //tokenStore.saveNewTokens(newTokens.accessToken, newTokens.refreshToken)

            // 重试所有队列中的请求
            failedQueue.forEach { it.invoke() }
            failedQueue.clear()

            // 重试原始请求
            addAuthHeader(originalRequest)
            client.request(originalRequest)
        } catch (e: Exception) {
            // 刷新失败处理
            tokenStore.removeAccessToken(tokenKey)
            redirectToLogin()
            throw e
        } finally {
            isRefreshing = false
        }
    }

    // 刷新Token请求
//    private suspend fun refreshToken(): TokenResponse {
//        return client.post("https://api.example.com/auth/refresh") {
//            setBody(RefreshRequest(TokenManager.getRefreshToken()))
//        }
//    }

    // 封装的API请求方法
    suspend inline fun <reified T> get(
        url: String,
        block: HttpRequestBuilder.() -> Unit = {}
    ): T {
        return client.request {
            method = HttpMethod.Get
            url(  url )
            addAuthHeader(this)
            block()
        }.body()
    }

    abstract fun redirectToLogin()
}